package com.sanhuo.idms;

import com.sanhuo.idms.entity.DormElectric;
import com.sanhuo.idms.service.DormElectricService;
import com.sanhuo.idms.service.ElectricScheduleDayService;
import com.sanhuo.idms.service.ElectricSheduleWeekService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.List;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Transactional
public class CronTask {
    @Autowired
    private ElectricScheduleDayService dayService;
    @Autowired
    private ElectricSheduleWeekService weekService;
    @Autowired
    private DormElectricService electricService;

    /**
     * 每四小时记录一次消耗
     *
     * @throws ParseException
     */
    @Scheduled(cron = "0 0 0,4,8,12,16,20,23 * * ?   ")
    @Async//多线程开启
//    @Transactional
    public void saveDay() throws ParseException {
        List<DormElectric> list = electricService.findAll();
        for (DormElectric electric : list) {
            dayService.save(electric.getDormId(), electric.getConsume());
        }
    }

    /**
     * 记录每天的消耗
     *
     * @throws ParseException
     */
    @Scheduled(cron = "0 59 23 * * ?   ")
    @Async//多线程开启

    public void saveWeek() throws ParseException {
        List<DormElectric> list = electricService.findAll();
        for (DormElectric electric : list) {
            weekService.save(electric.getDormId(), electric.getConsume());
        }
    }
}
